#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Introduction to Programming in Java - An Interdisciplinary Approach

All book programs ported to Python by
Scott C. King (revisionx at {gee}ma1l <dot> c0m).

All program examples pass Pylint with a perfect 10.00 score.
Pylint:  http://www.pylint.org/


# Exercise 1.3.40 - Game simulation (Let's Make a Deal)

Syntax:
python monty_hall_sim.py 10000


Notes:
int(sys.argv[1]) == Integer.parseInt(args[0])

sys is a required import here in order to use command line arguments.
https://docs.python.org/2/tutorial/stdlib.html

random is a required import as a substitute for Java's Math.random()
https://docs.python.org/2/library/random.html

xrange is preferred here (over range) due to it returning an xrange object
instead of a list (where large iteration counts could cripple the computer.)
https://docs.python.org/2/library/functions.html#xrange

What is that underscore doing in the for loop?  The _ can be used as a
placeholder for ignored members in for-loop and tuple assignments.
Otherwise, Pylint warns on the unused variable.

'''

import sys
import random


def main():
    ''' Perfrom Monty Hall game simulation '''

    try:
        iterations = int(sys.argv[1])
    except IndexError:
        print 'Integer for number of iterations is required!'
        print 'Syntax: "python monty_hall_sim.py 1000"'
        sys.exit(0)

    door = ['goat', 'goat', 'car']
    sw_win = 0
    sw_lose = 0

    for _ in xrange(iterations):
        random.shuffle(door)
        door_num = random.randrange(3)  # Select door #1, door #2, or door #3

        # Select door with goat (k != n and door[k] != "car")
        sequence = range(3)
        random.shuffle(sequence)
        for k in sequence:
            if k == door_num or door[k] == "car":
                continue

        # Perform the switch
        if door[door_num] == "car":
            sw_lose += 1
        else:
            sw_win += 1

    print "Switching produces {} wins and {} losses.".format(sw_win, sw_lose)
    win_percentage = (100.0 * sw_win) / (sw_win + sw_lose)
    print "By switching, you'll win {}% of the time!".format(win_percentage)


if __name__ == '__main__':
    main()
